package com.east.aspect;


import com.east.common.DataFilter;
import com.east.entity.User;
import com.east.query.BaseQuery;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;

@Component
@Aspect
public class UserListAspect {
    @Pointcut(value = "@annotation(com.east.common.DataFilter)")
    public void pointcut() {

    }

    @Around(value = "pointcut()")
    public Object beforeAdv(ProceedingJoinPoint joinPoint) throws Throwable {
        // 1. 获取登陆对象
        User loginUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer userId = loginUser.getId();
        // 2 如果是管理员 直接放行
        if (loginUser.getRoleList().contains("admin")) {
            return joinPoint.proceed();
        }
        // 3. 获取切入的方法
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        // 4. 获得注解
        DataFilter annotation = method.getAnnotation(DataFilter.class);
        String fieldName = annotation.fieldName();
        String tableAlias = annotation.tableAlias();
        // 5. 获得方法上的参数
        Object[] args = joinPoint.getArgs();
        Arrays.stream(args).forEach(arg -> {
            if (arg instanceof BaseQuery) {
                BaseQuery baseQuery = (BaseQuery) arg;
                String filterSql = "and " + tableAlias + "." + fieldName + "=" + userId;
                baseQuery.setFilterSql(filterSql);
                System.out.println(filterSql);
            }
        });
        return joinPoint.proceed();
    }
}
